<?php

namespace app\controller\api;

use app\BaseController;
use app\controller\Token;
use app\model\Admin;
use app\model\AuthRule;

class User extends BaseController
{
    //登录
    public function login()
    {
        $adminModel = new Admin();
        $postData = input();

        //检测账号密码是否正确
        if (!$adminModel->where(['username'=>$postData['pass'],'password'=>$postData['pwd']])->find()) {
            return json(['code'=>1,'msg'=>'账号或密码有误']);
        }

        //用户信息
        $user = [
            "id" => $adminModel->where(['username'=>$postData['pass'],'password'=>$postData['pwd']])->value('id'),
            "username" => $adminModel->where(['username'=>$postData['pass'],'password'=>$postData['pwd']])->value('username')
        ];
        $uid = $postData['pass'];//input('uid');//接收生成token字符串 如：123
        $token = signToken($uid);
        $adminModel->where(['username'=>$postData['pass'],'password'=>$postData['pwd']])->update(['token'=>$token]);
        return json(['code'=>200,'msg'=>'加载成功','token'=>$token]);
    }

    //获取菜单列表
    public function getMenuList() {
        $authRuleModel = new AuthRule();

        if (empty(request()->header('Authorization'))) {
            return json(['code'=>1,'msg'=>'token信息缺失']);
        }

        $token = str_replace('Bearer ','',request()->header('Authorization'));
        $rt = checkToken($token);
        if ($rt['code'] == 200) {
            $authRule = $authRuleModel->select()->toArray();
            return json(['code'=>200,'msg'=>'加载成功','data'=>buildTree($authRule)]);
        } else {
            return json(['code'=>$rt['code'],'msg'=>$rt['msg']]);
        }
    }
}
